package com.eportal.filter;

import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * CORS过滤器
 * Created by Saber on 16/4/25.
 */
@Component
public class SimpleCORSFilter implements Filter {


    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request =(HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;

//        Enumeration ee =request.getHeaderNames();                //通过枚举类型获取请求文件的头部信息集
//        //遍历头部信息集
//        while(ee.hasMoreElements()){
//        //取出信息名
//            String name=(String)ee.nextElement();
//        //取出信息值
//            String value=request.getHeader(name);
//            System.out.println(name + "=" + value);
//        }

        String curOrigin = request.getHeader("Origin");
        //String curOrigin = ((HttpServletRequest) req).getRequestURL().toString();
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
        response.setHeader("Access-Control-Allow-Origin", "*");
        chain.doFilter(req, res);
    }

    public void init(FilterConfig filterConfig) {}

    public void destroy() {}

}
